/**********************************************************************
 * SailmiPIM - modular cross-platform feature Personal Information Manager Tools.
 * Copyright(C) 2006-2014  Georg Rudoy
 *
 * Distributed under the Boost Software License, Version 1.0.
 *(See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
 **********************************************************************/

#pragma once

#include <QObject>
#include <sailmipim/core/irootwindowsmanager.h>
#include "mainwindow.h"

class QIcon;
class QScreen;

namespace SailmiPIM
{
	class TabManager;
	class MWProxy;

	class RootWindowsManager : public QObject
							 , public IRootWindowsManager
	{
		Q_OBJECT
		Q_INTERFACES(IRootWindowsManager)

		struct WinData
		{
			MainWindow *Window_;
			MWProxy *Proxy_;
			TabManager *TM_;
		};
		QList<WinData> Windows_;

		bool IsShuttingDown_ = false;
	public:
		RootWindowsManager(QObject* = nullptr);

		void Initialize();
		void Release();

		MainWindow* MakeMainWindow();
		TabManager* GetTabManager(MainWindow*) const;
		TabManager* GetTabManager(int) const;

		bool WindowCloseRequested(MainWindow*);

		QObject* GetQObject() override;

		int GetWindowsCount() const override;
		int GetPreferredWindowIndex() const override;
		int GetPreferredWindowIndex(const ITabWidget*) const;
		int GetPreferredWindowIndex(const QByteArray&) const override;
		int GetWindowForTab(ITabWidget*) const override;
		int GetWindowIndex(QMainWindow*) const override;

		IMWProxy* GetMWProxy(int) const override;
		MainWindow* GetMainWindow(int) const override;
		ICoreTabWidget* GetTabWidget(int) const override;

		void AddTab(const QString&, QWidget*, AddTabFlags) override;
	private:
		void ConnectSignals(QWidget*);

		MainWindow* CreateWindow(QScreen *screen, bool primary);

		template<typename F>
		void PerformWithSender(F&&);

		void MoveTab(int tab, int fromWin, int toWin);
		void CloseWindowTabs(int index);
	public slots:
		void moveTabToNewWindow();
		void moveTabToExistingWindow();
	private slots:
		void remove();
		void changeTabName(const QString&);
		void changeTabIcon(const QIcon&);
		void bringToFront();
	signals:
		void windowAdded(int) override;
		void windowRemoved(int) override;
		void currentWindowChanged(int, int) override;
		void tabAdded(int, QWidget*) override;
		void tabIsRemoving(int, QWidget*) override;
		void tabIsMoving(int, int, int) override;
		void tabMoved(int, int, int) override;

		void hookTabAdding(SailmiPIM::IHookProxy_ptr, QWidget*);
		void hookGetPreferredWindowIndex(SailmiPIM::IHookProxy_ptr, const QWidget*) const;
		void hookGetPreferredWindowIndex(SailmiPIM::IHookProxy_ptr, const QByteArray&) const;
		void hookGetPreferredWindowIndex(SailmiPIM::IHookProxy_ptr) const;
	};
}
